package sample.register;

import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import org.apache.commons.lang3.StringUtils;
import sample.Main;
import sample.login.User;
import sample.login.view.LoginFxmlView;
import sample.register.service.RegisterService;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author taowenchen
 */
@FXMLController
public class RegisterController {

    @Resource
    RegisterService registerService;


    @FXML
    private PasswordField password;

    @FXML
    private Label accountError;

    @FXML
    private Label passwordError;

    @FXML
    private TextField account;


    @FXML
    void register(ActionEvent event) throws IOException {
        final String accountText = account.getText();
        final String passwordText = password.getText();

        if (StringUtils.isAnyBlank(accountText)) {
            showError(accountError, "账户不能为空");
            return;
        }
        accountError.setOpacity(0);

        if (StringUtils.isAnyBlank(passwordText)) {
            showError(passwordError, "密码不能为空");
            return;
        }

        passwordError.setOpacity(0);
        final boolean register = registerService.register(User.builder().account(accountText).password(passwordText).build());
        if (!register) {
            showError(accountError, "账户已存在");
        }
        Main.showView(LoginFxmlView.class);
    }

    @FXML
    void registerBack(ActionEvent event) throws IOException {
        Main.showView(LoginFxmlView.class);
    }

    private void showError(Label accountError, String message) {
        accountError.setText(message);
        accountError.setTextFill(Color.RED);
        accountError.setOpacity(10);
    }

}
